<template>
  <div>
    <form @submit.prevent="onSearch">
      <input v-model="query" placeholder="输入关键词" />
      <button type="submit">搜索</button>
    </form>

    <div v-if="loading">正在搜索...</div>
    <ul v-else>
      <li v-for="item in results" :key="item.id">
        <a :href="item.url" target="_blank">{{ item.title }}</a>
        <p>{{ item.snippet }}</p>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      query: '',
      results: [],
      loading: false
    }
  },
  methods: {
    async onSearch() {
      if (!this.query) return
      this.loading = true
      try {
        const resp = await fetch(`/api/search?q=${encodeURIComponent(this.query)}`, {
          headers: { 'X-Real-IP': '127.0.0.1' }
        })
        if (!resp.ok) throw new Error('搜索失败')
        this.results = await resp.json()
      } catch (e) {
        console.error(e)
        alert('搜索失败，请稍后再试')
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style>
form { display: flex; gap: 8px; margin-bottom: 16px; }
input { flex: 1; padding: 8px; }
button { padding: 8px 16px; }
li { margin-bottom: 12px; }
p { margin: 4px 0 0; color: #555; }
</style>
